#!/bin/bash

function usage()
{
    echo "usage :$0 dest [param...]"
    echo "dest  :mysql [game|gm]"
    echo "      :redis"
    echo "      :mongo host"
}

if (($# < 1)); then
    usage
    exit 1
fi

###########################################################################
cd $(dirname $(readlink -f $0))


dest=$1
title="db $dest"

case "$dest" in
    mysql)
        mysql_ip=`./config/get.sh mysql.ip`
        mysql_port=`./config/get.sh mysql.port`
        mysql_user=`./config/get.sh mysql.user`
        mysql_password=`./config/get.sh mysql.password`
        mysql_charset=`./config/get.sh mysql.charset`
        if (($# >= 2)); then
            if (("gm" == "$2")); then
                mysql_ip=`./config/get.sh mysql.gm.ip`
                mysql_port=`./config/get.sh mysql.gm.port`
            fi
        fi
        mysql -h"$mysql_ip" -P$mysql_port -u"$mysql_user" -p"$mysql_password" --default-character-set=$mysql_charset
    ;;
    redis)
        hosts=(`./config/get.sh server.list redis`)
        host_count=${#hosts[*]}

        if [ $host_count -ne 1 ]; then
            ./util/error.sh "$title" "config error"
            exit 1
        fi

        host=${#hosts[0]}
        redis_ip=`./config/get.sh server.host.$host.redis.bind`
        redis_port=`./config/get.sh server.host.$host.redis.port`
        telnet $redis_ip $redis_port
    ;;
    mongo)
        if (($# < 2)); then
            usage
            exit 1
        fi

        host=$2
        mongo_ip=`./config/get.sh server.host.$host.ip`
        mongo_port=`./config/get.sh server.host.$host.mongo.port`
        if [ -z $mongo_port ]; then
            ./util/error.sh "$title" "$host invalid"
            exit 1
        fi

        mongo $mongo_ip:$mongo_port
    ;;
    *)
        usage
        exit 1
esac

